﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using umbraco.BasePages;
using umbraco.cms.presentation.Trees;
using umbraco.cms.businesslogic;
using System.Xml;
using System.Web.Script.Serialization;
using umbraco.BusinessLogic;
using System.IO;

namespace Marko.Portal.Shared.DataService
{
    public class NodeInfoDataService : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }
        public XmlTree xTree;
        public void ProcessRequest(HttpContext context)
        {
            Authorize();
            context.Response.ContentType = "application/json";            
            JavaScriptSerializer ser = new JavaScriptSerializer();
            if (NodeID>0) {
                ClientNode cn = new ClientNode(NodeID);                
                var res = ser.Serialize(cn);
                context.Response.Write(res);
            }
            else if (!string.IsNullOrEmpty(NodeData) && "fsobjects".Equals(AppTreeAlias, StringComparison.InvariantCultureIgnoreCase))
            {
                ClientNode cn = GetFileSystemInfoNode(NodeData); 
                
                var res = ser.Serialize(cn);
                context.Response.Write(res);
            }else context.Response.Write("");
        }

        private ClientNode GetFileSystemInfoNode(string NodeData)
        {
            ClientNode  result=new ClientNode ();
            result.CContentType=new ClientNode.ClientContentType();

            string path=Path.Combine(AppPath,NodeData);
            FileSystemInfo fsi= new DirectoryInfo(path);
            bool isfolder = true;
            if (!fsi.Exists) { fsi = new FileInfo(path); isfolder = false; }
            if (!fsi.Exists) {
                result.Title = "File haven't be found!";
                result.CContentTypeIcon="bin.png";
                result.ExceptionsCount = 1;
                
            } else {
                result.Title=NodeData;
                result.CContentTypeIcon =isfolder? "folder.gif":"doc.gif";
                result.Path = NodeData.Replace("//", "\\").Replace("\\", ","); ;
            };

            result.CContentType.IconUrl = result.CContentTypeIcon;
            return result;
        }

        public int NodeID
        {
            get
            {
                int num;                
                if (int.TryParse(NodeData, out num))
                    return num;
                return -1;
            }
        }

        public string NodeData
        {
            get { return HttpContext.Current.Request.QueryString["id"] ?? ""; }
        }
        public string AppTreeAlias
        {
            get
            {
                return HttpContext.Current.Request.QueryString["treeType"] ?? "";
            }
        }
        public string AppPath
        {
            get
            {
                return HttpContext.Current.Request.PhysicalApplicationPath;
            }
        }
        public static void Authorize()
        {
            if (!BasePage.ValidateUserContextID(BasePage.umbracoUserContextID))
            {
                throw new Exception("Client authorization failed. User is not logged in");
            }
        }


    }
    public class ClientNode
    {
        public ClientNode(){}
        public ClientNode(int CMSNodeId)
        {
            try
            {
                InitData(new CMSNode(CMSNodeId));
            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Error, CMSNodeId, ex.Message);
                this.Title = ex.Message;
                this.CContentTypeIcon = "bin.png";
                ExceptionsCount++;
            }
        }
        
        public ClientNode(CMSNode Node)
        {
            InitData(Node);            
        }

        private void InitData(CMSNode Node)
        {
            if (Node == null) return;
            BeenReturned = 1;
            Title = Node.Text;
            ChildCount = Node.ChildCount;
            DefaultEditorURL = Node.DefaultEditorURL;
            HasChildren = Node.HasChildren;
            Id = Node.Id;
            Image = Node.Image;
            IsTrashed = Node.IsTrashed;
            Level = Node.Level;
            nodeObjectType = Node.nodeObjectType;
            OpenImage = Node.OpenImage;
            ParentId = Node.ParentId;
            Path = Node.Path;
            sortOrder = Node.sortOrder;
            UniqueId = Node.UniqueId;

            umbraco.cms.businesslogic.Content c = null;
            try
            {
                c = new umbraco.cms.businesslogic.Content(Node.Id);
                var s = GetTreePath(Node);
                TreePath = String.IsNullOrEmpty(s) ? Node.Text : s;
            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Error, Node.Id, ex.Message);
                ExceptionsCount++;
            }

            if (c != null)
            {
                CContentType = new ClientContentType(c.ContentType);
                CContentTypeIcon = c.ContentTypeIcon;
                CVersion = c.Version;
                CVersionDate = c.VersionDate;
            }
        }

        private string GetTreePath(CMSNode Node)
        {
            return Node.ParentId > 0 ? GetTreePath(Node.Parent) + "/" + Node.Text : Node.Text;         
        }


        public int BeenReturned { get; set; }//needs to indicate that data has been returned from the service
        public string Title{get;set;}
        public string TreePath { get; set; }
        public int ChildCount { get; set; }
        public string DefaultEditorURL { get; set; }
        public bool HasChildren { get; set; }
        public int Id{ get; set; }
        public string Image { get; set; }
        public bool IsTrashed { get; set; }
        public int Level { get; set; }
        public Guid nodeObjectType { get; set; }
        public string OpenImage { get; set; }
        public int ParentId { get; set; }
        public string Path { get; set; }
        public int sortOrder { get; set; }
        public Guid UniqueId { get; set; }


        public ClientContentType CContentType { get; set; }
        public string CContentTypeIcon { get; set; }
        public Guid CVersion { get; set; }
        public DateTime CVersionDate { get; set; }
        public int ExceptionsCount{ get; set; }


        public class ClientContentType
        {
            public ClientContentType ()
	        { }

            public ClientContentType(ContentType cType)
            {
                if (cType == null) return;
                Alias = cType.Alias;
                AllowedChildContentTypeIDs = cType.AllowedChildContentTypeIDs;
                Description=cType.Description;
                IconUrl=cType.IconUrl;
                Id=cType.Id;
                Image=cType.Image;
                IsTrashed=cType.IsTrashed;
                Level=cType.Level;
                MasterContentType=cType.MasterContentType;
                Title=cType.Text;
                Thumbnail=cType.Thumbnail;
                UniqueId=cType.UniqueId;
            }
            public string Alias { get; set; }
            public int[] AllowedChildContentTypeIDs { get; set; }
            public string Description { get; set; }
            public string IconUrl { get; set; }
            public int MasterContentType { get; set; }
            
            public string Thumbnail { get; set; }
            public int Id { get; set; }
            public string Image { get; set; }
            public bool IsTrashed { get; set; }
            public int Level { get; set; }
            public string Title { get; set; }
            public Guid UniqueId { get; set; }
        }
    }

}
